package com.ada.sqlSession;

import com.ada.config.BoundSql;
import com.ada.pojo.Configuration;
import com.ada.pojo.MappedStatement;
import com.ada.utils.*;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    public PreparedStatement generateStatement(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception{
        //1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();
        /**
         * 2.获取sql语句        select * from user where id = #{id} and username = #{username}
         * 转换sql语句        select * from user where id = ？ and username = ？
         * 对参数值进行解析存储
         */
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //3.获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //解析出来sql里的参数名，对应参数类的字段名
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();

        //4.设置参数
        //获取参数对象全路径
        String paramterType = mappedStatement.getParamterType();
        //参数类型可能为空，如果为空则parameterMappingList也为空，下面for循环不会执行
        Class<?> paramterTypeClass = getClassType(paramterType);
        if(paramterTypeClass == null && parameterMappingList.size()>0){
            throw new RuntimeException("参数格式配置错误(有参数但是没有参数类型)！");
        }
        if(paramterTypeClass != null && parameterMappingList.size() == 0){
            throw new RuntimeException("参数格式配置错误(有参数类型，但是没有对应参数)！");
        }
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            if(TypeCheck.isBaseType(paramterTypeClass.getSimpleName().toUpperCase())){
                preparedStatement.setObject(i + 1, params[i]);
                continue;
            }

            //反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }

    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement=generateStatement(configuration,mappedStatement,params);
        try {
            preparedStatement.execute();
            int rows = preparedStatement.getUpdateCount();
            return rows;
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement=generateStatement(configuration,mappedStatement,params);
        //5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();
        //6.封装返回结果集
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //获取字段名
                String columnName = metaData.getColumnName(i);
                //字段的值
                Object value = resultSet.getObject(columnName);
                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            Class<?> clazz = Class.forName(paramterType);
            return clazz;
        }
        return null;
    }

    /**
     * 要换成sql的转换 1.对#{}使用?进行替换，2.解析出#{}进行存储
     *
     * @param sql
     * @return BoundSql包含完成转换的sql语句，还有对应的参数
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类对占位符做解析工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //#{}解析出来的参数名
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        //封装
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }
}
